import { FC, ChangeEvent, useState, useEffect } from "react";
import { Input } from "antd";
import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
import { KEYWORD_KEY } from "../constant";

const { Search } = Input;

const ListSearch: FC = () => {
  const nav = useNavigate();
  const { pathname } = useLocation();
  const [searchParams] = useSearchParams();
  const [value, setValue] = useState("");

  useEffect(() => {
    setValue(searchParams.get(KEYWORD_KEY) || "");
  }, [searchParams]);

  function handleChange(event: ChangeEvent<HTMLInputElement>) {
    setValue(event.target.value);
  }

  function handleSearch(value: string) {
    nav({
      pathname,
      search: `${KEYWORD_KEY}=${value}`,
    });
  }

  return (
    <Search
      size="large"
      placeholder="请搜索"
      allowClear
      value={value}
      onChange={handleChange}
      onSearch={handleSearch}
      style={{ width: "260px" }}
    ></Search>
  );
};

export default ListSearch;
